package com.zh.springcloud.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;

import javax.sql.DataSource;

/**
 * @Description: Security 配置类
 * @ClassName SecurityConfig
 * @date: 2021.10.17 14:44
 * @Author: zhanghang
 *
 * WebSecurityConfigurerAdapter 类是个适配器,我们如果想自定义一下配置的话需要继承这个类，从写他的方法
 */
@Configuration
@EnableWebSecurity  // 开启 WebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {


	/**
	 * description: 密码解析器
	 * date: 2021年-10月-17日 14:47
	 * author: zhanghang
	 * SpringSecurity 要求：当自定义登录逻辑时容器内必须有 PasswordEncoder实例，所以不能直接new对象
	 * @param
	 * @return org.springframework.security.crypto.password.PasswordEncoder
	 */
	@Bean
	public PasswordEncoder pw(){
		return new BCryptPasswordEncoder();
	}


	/**
	 * description: 这个方法是关于 http 请求的认证策略方面的设置
	 * date: 2021年-10月-17日 15:23
	 * author: zhanghang
	 *
	 * @param http
	 * @return void
	 */
	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.authorizeRequests()
				// 放行端点服务
				.antMatchers("/oauth/**").permitAll()
				// 放行登录登出
				.antMatchers("/login/**","/logout/**").permitAll()
				.anyRequest().authenticated()
				.and()
				// 放行表单提交
				.formLogin().permitAll()
				.and()
				// 关闭csrf
				.csrf().disable();

	}

	/**
	 * description: 密码模式需要用到的Bean
	 * date: 2021年-11月-14日 19:40
	 * author: zhanghang
	 * 
	 * @param 
	 * @return org.springframework.security.authentication.AuthenticationManager
	 */ 
	@Bean
	@Override
	public AuthenticationManager authenticationManager() throws Exception {
		return super.authenticationManager();
	}

}
